package com.rt.tmpt.controller.springmvc.admin;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.rt.tmpt.dto.*;
import com.rt.tmpt.service.IMenuService;
import com.rt.tmpt.service.ISecurityV2Service;
import com.rt.tmpt.utils.StringUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@ApiIgnore
@Controller
@RequestMapping("/admin123/right_v2")
@Slf4j
public class SecurityV2Action {


    @Resource
    private ISecurityV2Service securityV2Service;
    @Resource
    private IMenuService menuService;

    /**
     * Vue 对接完成
     * 查询角色列表
     *
     * @return
     */
    @GetMapping(value = "/roleList")
    @ResponseBody
    public Result queryRoleList() {
        Result result = new Result();
        try {
            result = securityV2Service.queryA2RoleList();
        } catch (Exception e) {
            e.printStackTrace();
            result.fault("系统出错:" + e.getLocalizedMessage());
        }
        return result;
    }


    /**
     * Vue
     * bind auths -> role
     *
     * @return
     */
    @ApiOperation(value = "角色管理-权限管理-添加权限菜单")
    @PostMapping(value = "/saveMyAuthsByRoleId")
    @ResponseBody
    public Result saveMyAuthsByRoleId(@RequestBody Map<String, String> paramMap,
                                      HttpServletRequest request) {
        String roleId = paramMap.get("roleId");
        String menuIdArr = paramMap.get("menuIdArr");
        // {"d_102":"0","d_38":"0","d_41":"0","d_43":"0","d_7599":"10","d_9632":"10"} // d_menuId
        String dataLimitType = paramMap.get("dataLimitType");
        Map dataLimitTypeMap = JSONObject.parseObject(dataLimitType);

        String[] menuIdArr1 = menuIdArr.trim().split(",");
        //取消这个角色所有权限
        if (StringUtils.isNull(menuIdArr.trim())) {
            menuIdArr1 = new String[]{};
        }

        A1OperationlogDto oprDtoBack = new A1OperationlogDto(request, A1OperationlogDto.UserTypeBack);
        Result resultObj = new Result();
        try {
            resultObj = menuService.bindAuths2Role(Long.parseLong(roleId), menuIdArr1, dataLimitTypeMap, oprDtoBack);
        } catch (Exception e) {
            e.printStackTrace();
            resultObj.fault(e.getLocalizedMessage());
        }
        return resultObj;
    }

    /**
     * Add a role
     *
     * @return
     */
	/*@ApiOperation(value = "角色管理-权限管理-添加权限菜单")
	@RequestMapping(value = "/securityv2Ajax_addRole")
	@ResponseBody
	public Result addRole(String roleJsonArray, String roleId,
                          HttpServletRequest request){
		//[{"menuId":9,"menuParentId":0,"dataLimitType":0},{"menuId":10,"menuParentId":9,"dataLimitType":"0"},{"menuId":11,"menuParentId":10,"dataLimitType":0},
		// {"menuId":12,"menuParentId":10,"dataLimitType":0},{"menuId":1,"menuParentId":0,"dataLimitType":0},{"menuId":2,"menuParentId":1,"dataLimitType":0},
		// {"menuId":3,"menuParentId":2,"dataLimitType":"0"},{"menuId":4,"menuParentId":2,"dataLimitType":"0"}]
		//roleJsonArray
		A1OperationlogDto oprDtoBack = new A1OperationlogDto(request, A1OperationlogDto.UserTypeBack);
		Result resultObj = new Result();
		try{
			resultObj = menuService.bindRole_Menu(Long.parseLong(roleId), roleJsonArray, oprDtoBack);
		}catch (Exception e) {
			e.printStackTrace();
			resultObj.fault(e.getLocalizedMessage());
		}
		return resultObj;
	}*/
    @ApiOperation(value = "角色管理-权限管理-查询菜单列表")
    @GetMapping(value = "/securityv2Ajax_queryMenus4RoleConfByRoleId")
    @ResponseBody
    public Result queryMenus4RoleConfByRoleId(String roleId) {
        Result result = new Result();
        try {
            result = menuService.queryMenus4RoleConfByRoleId(Long.parseLong(roleId));
        } catch (Exception e) {
            e.printStackTrace();
            result.fault();
        }
        return result;
    }


    /**
     * 查询用户所拥有的角色列表
     *
     * @return
     */
    @GetMapping(value = "/securityv2Ajax_queryRoleListByUserid")
    @ResponseBody
    public String queryRoleListByUserid(String _userId) {
        Result result = new Result();
        try {
            Result<A2RoleDto> resultObj = securityV2Service.queryA2RoleList();
            Result<A2RoleDto> resultObjMy = securityV2Service.queryA2RoleListByUser(Long.parseLong(_userId));
            if (!resultObj.isSuccess()) {
                return "";
            }
            List<A2RoleDto> roleDtoList = resultObj.getList();

            List<A2RoleDto> roleDtoListMy = resultObjMy.getList();
            List<Long> roleDtoListMyLong = new ArrayList<Long>();
            for (A2RoleDto roleDtoMy : roleDtoListMy) {
                roleDtoListMyLong.add(roleDtoMy.getId());
            }
            for (A2RoleDto roleDto : roleDtoList) {
                //JSONObject jo = new JSONObject();
                Map<String, Object> jo = new HashMap<String, Object>();
                jo.put("id", roleDto.getId());
                jo.put("text", roleDto.getRoleName());
                if (roleDtoListMyLong.contains(roleDto.getId())) {
                    jo.put("checked", "true");
                }
                result.getList().add(jo);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.fault("系统出错:" + e.getLocalizedMessage());
        }
        return new Gson().toJson(result.getList());
    }

    /**
     * Vue
     * 更新用户角色列表
     *
     * @return
     */
    @RequestMapping(value = "/securityv2Ajax_updateRoleListByUserid")
    @ResponseBody
    public Result updateRoleListByUserid(String selectedRoleNodes, String userId,
                                         HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        A1OperationlogDto oprDtoBack = new A1OperationlogDto(request, A1OperationlogDto.UserTypeBack);
        try {
            JSONArray jarr = new JSONArray(selectedRoleNodes);
            List<Long> roleIdList = new ArrayList<Long>();
            for (int i = 0; i < jarr.length(); i++) {
                roleIdList.add(Long.valueOf(jarr.getInt(i)));
            }

            result = securityV2Service.bindUser_Role(Long.parseLong(userId), roleIdList, oprDtoBack);

        } catch (Exception e) {
            e.printStackTrace();
            result.fault("系统出错:" + e.getLocalizedMessage());
        }
        return result;
    }


    /**
     * 不用权限，直接放行的标识：_access
     *
     * @return
     */
    @RequestMapping(value = "/securityv2Ajax_getCompanyDeptTree_access", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getCompanyDeptTree_access(
            HttpServletRequest request, HttpServletResponse response) {
        Result resultObj = new Result();
        A1OperationlogDto oprDtoBack = new A1OperationlogDto(request, A1OperationlogDto.UserTypeBack);
        try {
            resultObj = securityV2Service.queryA2CompnayList(null);
            List<A2CompanyDto> a2CompanyDtoList = resultObj.getList();

            resultObj.getList().clear();
            for (A2CompanyDto companyDto : a2CompanyDtoList) {
                String companyId = String.valueOf(companyDto.getId());
                String companyName = companyDto.getName();
                Map<String, Object> joCompany = new HashMap<String, Object>();
                joCompany.put("id", "c" + companyId);
                joCompany.put("text", companyName);

                List<Map<String, Object>> jarrDept = new ArrayList<Map<String, Object>>();
                for (A2DeptDto deptDto : companyDto.getA2DeptDtoList()) {
                    String deptId = String.valueOf(deptDto.getId());
                    String deptName = deptDto.getName();
                    Map<String, Object> joDept = new HashMap<String, Object>();
                    //JSONObject joDept = new JSONObject();
                    joDept.put("id", deptId);
                    joDept.put("text", deptName);
                    jarrDept.add(joDept);
                }
                joCompany.put("children", jarrDept);
                resultObj.getList().add(joCompany);
            }

            //String json = this.jsonArrayResult.toString();
            //System.out.println("==================:"+json);
        } catch (Exception e) {
            e.printStackTrace();
            //this.result = "操作失败："+e.getLocalizedMessage();
        }
        return new Gson().toJson(resultObj.getList());
    }


}
